import json

from flask import Blueprint, jsonify, request

from utils.db import db1
from utils.redisconn import r
from utils.comm import get_data,gettree

bp_workflow = Blueprint('workflow',__name__)


@bp_workflow.route('/worklist')
def worklist():
    sql = "select * from workflow"
    res = db1.find_all(sql)
    return jsonify({'code':200,'list':res})


@bp_workflow.route("/getsource")
def getsource():
    values = r.get_str("datasource")
    if values:
        lst = eval(values)
    else:
        sql = "select * from data_source"
        res = db1.find_all(sql)
        lst = []
        if res:
            for i in res:
                dic = {"id":i["id"],"name":i["name"]}
                msql = "select id,name,type from %s"%i["tablename"]
                mres = db1.find_all(msql)
                dic["mes"] = mres
                lst.append(dic)
        r.set_str("datasource",json.dumps(lst))

    return jsonify({"code":200,"list":lst})

@bp_workflow.route('/addworkflow',methods=["POST"])
def addworkflow():
    data = get_data()
    sql = "select * from workflow where id=%d"%int(data["id"])
    res = db1.find(sql)
    if res:
        usql = "update workflow set params='%s' where id=%d"%(str(data["list"]),int(res["id"]))
        db1.update(usql)
    return jsonify({"code":200,"msg":"修改成功"})

# 查询工作流
@bp_workflow.route("/query_workflow")
def query_workflow():
    sql = "select * from workflow"
    res = db1.find_all(sql)
    return jsonify({"code":200,"list":res})



# # 添加
# @bp_workflow.route('/addworkflows')
# def addworkflow():
#     data = get_data()
#     print(data)
#
#     return jsonify({'code':200,'mes':'ok'})
@bp_workflow.route('/taskm', methods=['POST'])
def taskm():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form

    title = data['title']
    params = data['params']
    auditids = data['auditids']
    # 添加任务
    sql = "insert into task(title,params,next_audit,status,nexta) values('%s','%s','%s',1,%d)" % (
    title, params, auditids, auditids[0])
    db1.update(sql)

    sql1 = "select id,title from task where title='%s'" % (title)
    task = db1.find(sql1)
    # 把当前任务加到redis中，选用hash类型
    key = 'task%d' % (auditids[0])
    r.insert_hash(key, task['id'], task['title']) 
    return jsonify({"code": 200})


# 展示带用户的无限极分类
@bp_workflow.route('/getdept')
def getdept():
    sql = "select * from dept"

    res = db1.find_all(sql)

    list1 = gettree(res)

    return jsonify({'code':200,'list':list1})









